<template>
  <div class="container">
    <!-- <p class="titlep" @click="gopath('/login')">
      <svg-icon class="logo" icon-class="logo" />
      <span>数字化综合服务平台</span>
    </p> -->
    <div class="topbox">
      <p class="titlep" @click="gopath('/login')">
        <svg-icon class="logoFp" icon-class="logo" />
        <span>数字化综合服务平台</span>
      </p>
      <img src="../../assets/img_top.png" alt="">
    </div>
    <el-row>
      <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
        <div class="centerbox maxScreen">
          <el-steps :space="300" :active="active" align-center>
            <el-step title="输入邮箱" />
            <el-step title="重置密码" />
            <el-step title="重置成功" />
          </el-steps>
          <div v-if="active == 1" class="formbox">
            <!-- <p class="formtitle">重置密码</p> -->
            <el-form ref="form" :rules="rules" :model="form" label-width="0px">
              <!-- <el-form-item prop="tenantId">
                <el-select ref="tenantId" v-model="form.tenantId" name="tenantId" placeholder="请选择租户" clearable style="width: 100%;">
                  <el-option
                    v-for="item in selectList"
                    :key="item.tenantId"
                    :label="item.tenantName"
                    :value="item.tenantId"
                  />
                </el-select>
              </el-form-item> -->
              <el-form-item label="" prop="email">
                <el-input v-model="form.email" placeholder="请输入邮箱" />
              </el-form-item>
              <!-- <el-form-item label="" prop="verCode">
                <el-input
                  v-model="form.verCode"
                  placeholder="请输入图片验证码"
                />
                <img class="verCode" :src="verImage" alt="" @click="getcaptchimg">
              </el-form-item> -->
              <el-button
                class="nextbtn"
                type="primary"
                :disabled="disabled"
                @click="validatorEmai(2)"
              >下一步</el-button>
              <p class="tips">
                提示：如果您的邮箱不可使用，请您通过其他方式联系系统管理员
              </p>
            </el-form>
          </div>
          <div v-if="active == 2" class="formbox">
            <!-- <p class="formtitle formtitle2">重置密码</p> -->
            <el-form ref="form" :rules="rules" :model="form" label-width="0px">
              <el-form-item label="" prop="emailCode">
                <el-input
                  v-model="form.emailCode"
                  maxlength="6"
                  placeholder="请输入邮箱验证码"
                />
                <!-- <span v-if="!emailflag" class="fs" @click="sendemailcode(2)">发送验证码</span> -->
                <span v-if="emailflag" class="wsd">未收到？</span>
                <span v-if="emailflag && totaltime > 0" class="zfs">{{
                  zfscontent
                }}</span>
                <span
                  v-if="emailflag && totaltime <= 0"
                  class="zfs"
                  @click="creatSlider()"
                >{{ zfscontent }}</span>
              </el-form-item>
              <el-form-item label="" prop="newPassword">
                <el-input
                  v-model="form.newPassword"
                  type="password"
                  :placeholder="`请输入${pwdregcon}`"
                />
              </el-form-item>
              <el-form-item label="" prop="surepassword">
                <el-input
                  v-model="form.surepassword"
                  type="password"
                  placeholder="确认密码"
                />
              </el-form-item>
              <el-button class="nextbtn2" @click="gopro(1)">上一步</el-button>
              <el-button
                class="nextbtn2"
                type="primary"
                @click="onSubmit(3, true)"
              >完成</el-button>

              <!-- <el-button
                class="nextbtn2"
                type="primary"
                @click="onSubmit(3, false)"
              >下一步</el-button> -->
            </el-form>
          </div>
          <!-- <div v-if="active == 3 && !okflag" class="formbox">
            <p class="formtitle">重置密码</p>
            <el-form ref="form" :rules="rules" :model="form" label-width="0px">
              <el-form-item label="" prop="newPassword">
                <el-input
                  v-model="form.newPassword"
                  type="password"
                  placeholder="请设置您的密码（6-20位，包含大小写字母、数字）"
                />
              </el-form-item>
              <el-form-item label="" prop="surepassword">
                <el-input
                  v-model="form.surepassword"
                  type="password"
                  placeholder="确认密码"
                />
              </el-form-item>
              <el-button
                class="nextbtn"
                type="primary"
                @click="onSubmit(3, true)"
              >完成</el-button>
            </el-form>
          </div> -->
          <div v-if="active == 3 && okflag" class="formbox">
            <p class="oktitle" style="margin-top: 100px">
              <svg-icon class="logoFp" icon-class="ok" />
              <span style="margin-left: 10px">重置成功</span>
            </p>
            <p class="okcontent">
              提示：系统将会在<span style="color: red">{{ timenum }}</span>秒内跳转至登录页面...
            </p>
            <el-button
              style="width: 70%"
              class="nextbtn"
              type="primary"
              @click="gopath('/login')"
            >直接登录</el-button>
          </div>
          <div class="goback" @click="gopath('/login')">
            <svg-icon class="logoFp" icon-class="back" />
            <span>返回登录</span>
          </div>
          <dtDialog
            ref="dialogPopupRef"
            class="slide-dialog"
            :title="dialogTitle"
            :visible.sync="dialogFormVisible"
            :width="'480px'"
            :is-loading="loading"
            :footer-slot="true"
            :footer-hidden="true"
            :screen-hidden="true"
            :append-to-body="true"
          >
            <div slot="content">
              <div>
                <dt-dragVerify
                  ref="dialogopen"
                  :l="42"
                  :r="10"
                  :w="slideVerifyWidth"
                  :h="218"
                  :block_y="block_y"
                  :imgurl="imgurl"
                  :miniimgurl="miniimgurl"
                  :slider-text="text"
                  @success="onSuccess"
                  @refresh="onRefresh"
                />
              </div>
            </div>
          </dtDialog>
        </div>
      </el-col>
    </el-row>

  </div>
</template>

<script>
import {
  sendMailCode,
  validatorEmailAuthCode
} from '@/framework/api/user'
import { getSliderKaptcha, getTenantDropDownList } from '@/framework/api/user'
import { checkEmail } from '@/framework/utils/validate'
import { encryption } from 'DQBasic-vue-component'
import { getPwdRole } from '@/framework/api/sysUser'
export default {
  name: 'ForgetPw',
  data() {
    const validateEmail = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入邮箱'))
      } else if (!checkEmail(value)) {
        callback(new Error('邮箱格式不正确'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback('请输入新密码')
      } else if (this.pwdreg.test(value) === false) {
        callback(this.pwdregcon)
      } else {
        callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      dialogTitle: '滑块验证',
      dialogFormVisible: false,
      miniimgurl: '',
      loading: false,
      imgurl: '',
      slideVerifyWidth: 432,
      block_y: 0,
      active: 1,
      form: {
        tenantId: '000000',
        email: '',
        verKey: '',
        verCode: '',
        newPassword: '',
        surepassword: '',
        verKeyEmail: '',
        emailCode: ''
      },
      rules: {
        tenantId: [{ required: true, trigger: 'change', message: '请选择租户' }],
        email: [
          { required: true, trigger: 'change', validator: validateEmail }
          // { required: true, trigger: 'blur', validator: validatePhone }
        ],
        verCode: [
          { required: true, trigger: 'blur', message: '请输入图片验证码' }
        ],
        emailCode: [
          { required: true, trigger: 'blur', message: '请输入邮箱验证码' }
        ],
        newPassword: [
          { required: true, trigger: 'blur', validator: validatePassword }
        ],
        surepassword: [
          { required: true, trigger: 'blur', validator: validatePass }
        ]
      },
      emailflag: false,
      okflag: false,
      selectList: [],
      timenum: 3,
      timer: '',
      zfscontent: '60s后再次发送',
      totaltime: 60,
      timer2: null,
      verImage: '',
      disabled: false,
      emailRequestId: '',
      text: '测试',
      kaptchaRequestId: '',
      pageKaptchaWidth: '',
      pwdreg: '',
      pwdregcon: '',
      pwdrole: ''
    }
  },
  mounted() {
    this.getcaptchimg()
    this.getSelect()
  },
  methods: {
    // 获取密码策略
    getPwdRole() {
      getPwdRole().then(res => {
        this.pwdrole = res.data
        this.pwdreg = new RegExp(this.pwdrole.pwdRegularExpression)
        this.pwdregcon = this.pwdrole.pwdRgDescribe
      })
    },
    // 获取图片验证码
    getcaptchimg() {
      // getcaptch().then((res) => {
      //   if (res.success) {
      //     this.verImage = res.data.verImage
      //     this.form.verCode = ''
      //     this.form.verKey = res.data.verKey
      //   }
      // })
    },
    gopath(path) {
      this.$router.push({
        path: path
      })
    },
    // 获取租户下拉框
    getSelect() {
      getTenantDropDownList().then((res) => {
        this.selectList = res.data
      })
    },
    gopro(n) {
      this.disabled = false
      this.active = n
      this.verImage = ''
      this.form.verCode = ''
      this.getcaptchimg()
    },
    onSubmit(n, flag) {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // if (n == 3 && !flag) {
          //   // this.active = n
          //   const obj2 = {
          //     email: this.form.email,
          //     verKeyEmail: this.form.verKeyEmail,
          //     verCodeEmail: this.form.verCodeEmail
          //   }

          //   // 第二步到第三步 需要校验邮箱验证码
          //   validatorEmailAuthCode(obj2).then((res) => {
          //     if (res.success) {
          //       this.$message({
          //         message: '验证成功',
          //         type: 'success'
          //       })
          //       this.active = n
          //       this.okflag = false
          //     } else {
          //       this.$message({
          //         message: res.message,
          //         type: 'error'
          //       })
          //     }
          //   })
          // }
          // 完成跳转登录
          if (n === 3 && flag) {
            this.okflag = false
            const obj3 = {
              email: this.form.email,
              newPwd: this.form.newPassword,
              emailRequestId: this.emailRequestId,
              emailCode: this.form.emailCode
            }
            const password = encryption({
              data: obj3
            })

            validatorEmailAuthCode(password).then((res) => {
              if (res.success) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.active = n
                this.okflag = true
                if (!this.timer) {
                  this.timenum = 3
                  this.timer = setInterval(() => {
                    if (this.timenum > 0 && this.timenum <= 3) {
                      this.timenum--
                    } else {
                      clearInterval(this.timer)
                      this.timer = null
                      // 先退出清空
                      // this.$store.dispatch('user/logout')
                      this.$router.push({
                        path: '/login'
                      })
                    }
                  }, 1000)
                }
              } else {
                this.$message({
                  message: res.message,
                  type: 'error'
                })
              }
            })
          }
        }
      })
    },
    time60() {
      this.emailflag = true
      this.totaltime = 60
      this.zfscontent = this.totaltime + 's后再次发送'
      if (!this.timer2) {
        this.timer2 = setInterval(() => {
          if (this.totaltime > 0 && this.totaltime <= 60) {
            this.totaltime--
            this.zfscontent = this.totaltime + 's后再次发送'
          } else {
            clearInterval(this.timer2)
            this.timer2 = null
            this.zfscontent = '再次发送'
          }
        }, 1000)
      }
    },
    // 第一步校验邮箱和图片验证码
    validatorEmai(n) {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.creatSlider()
        }
      })
    },
    handleStep(n) {
      // this.disabled = true
      // setTimeout(() => {
      //   this.getcaptchimg()
      // }, 2000)

      // tovalidatorEmai(obj)
      //   .then((res) => {
      //     if (res.success) {
      //       this.sendemailcode(n) // 第一步校验成功，进行发送验证码
      //     } else {
      //       this.$message({
      //         message: res.message,
      //         type: 'error'
      //       })
      //     }
      //   })
      //   .catch(() => {
      //     setTimeout(() => {
      //       this.disabled = false
      //     }, 2000)
      //   })
      this.sendemailcode(n) // 第一步校验成功，进行发送验证码
    },
    // 第二步 发送邮箱验证码
    sendemailcode(n) {
      const obj1 = {
        email: this.form.email,
        moveLength: this.form.moveLength,
        tenantId: this.form.tenantId,
        kaptchaRequestId: this.kaptchaRequestId,
        pageKaptchaWidth: this.slideVerifyWidth
      }
      this.loading = true
      sendMailCode(obj1).then((res) => {
        if (res.success) {
          this.$message({
            message: '发送成功',
            type: 'success'
          })
          this.time60()
          // this.form.verKeyEmail = res.data
          // this.form.verCodeEmail = ''
          this.emailRequestId = res.data.emailRequestId
          this.active = n
          this.dialogFormVisible = false
          this.loading = false
          this.pwdrole = res.data.pwdConfig
          this.pwdreg = new RegExp(this.pwdrole.pwdRegularExpression)
          this.pwdregcon = this.pwdrole.pwdRgDescribe
        }
      }).catch(res => {
        this.loading = false
        // 如果错误 则刷新验证码
        if (res.code === 'A22103' && this.$refs.dialogopen) { // 图片验证码失败
          this.onRefresh()
        } else {
          this.dialogFormVisible = false
        }
      })
    },
    //  滑块
    // 生成滑块验证吗
    creatSlider() {
      var that = this
      getSliderKaptcha().then(async res => {
        var imgobj = res.data
        that.block_y = imgobj.yHeight
        that.imgurl = 'data:image/jpg;base64,' + imgobj.backgroundImage
        that.miniimgurl = 'data:image/png;base64,' + imgobj.sliderImage
        that.kaptchaRequestId = imgobj.kaptchaRequestId
        this.dialogTitle = '滑块验证'
        this.dialogFormVisible = true
        await this.$nextTick()
        this.$refs.dialogopen.reset()
      })
    },
    // 刷新
    onRefresh() {
      this.imgurl = ''
      this.miniimgurl = ''
      this.creatSlider()
    },
    // 滑动结束，后台验证, l是滑动距离
    onSuccess(l) {
      // 将 滑块参数  表单参数  处理到this.loginForm里 统一调用账密登录接口
      this.form.kaptchaRequestId = this.kaptchaRequestId
      this.form.moveLength = l
      this.form.pageKaptchaWidth = this.slideVerifyWidth
      // this.accountLoginSavaData()
      this.handleStep(2)
    }
  }
}
</script>
<style lang="scss">
.formbox .el-input--medium .el-input__inner {
  height: 50px;
  line-height: 50px;
}
.formbox .el-form-item {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 46px;
}
.formbox .el-form-item .el-form-item__content {
  flex: 1;
  width: 100%;
  display: flex;
  align-items: center;
  .el-input {
    flex: 1;
  }
  .verCode {
    width: 100px;
    height: 50px;
    background: chocolate;
    margin-left: 20px;
    cursor: pointer;
    border: 1px solid #f7f7ff;
  }
}
</style>
<style lang="scss" scoped>
@import "~@/framework/styles/variables.scss";
.container{
  height: 100%;
  display: flex;
  flex-direction: column;
}
::v-deep .el-row{
  flex:1;
    display: flex;
    justify-content: center;
}
.tips {
  color: #e53013;
  text-align: center;
  font-size: 10px;
  white-space: nowrap;
}
.titlep {
  position: absolute;
  // top: 20%;
  left: 5%;
  display: flex;
  align-items: center;
  .logoFp {
    width: 50px !important;
    height: auto !important;
    max-height: 50px !important;
    margin-right: 10px;
  }
  span {
    font-size: 22px;
    font-family: Segoe UI;
    font-weight: 600;
    line-height: 0px;
    color: #ffffff;
    opacity: 1;
  }
}
.topbox {
  position: relative;
  z-index: 1;
  img {
    width: 100%;
    z-index: 2;
  }
}
.centerbox {
  position: relative;
  background: #ffffff;
  opacity: 1;
  border-radius: 4px;
  max-height: 604px;
  height: 95%;
  z-index: 9;
  padding-top: 20px;
  .el-steps {
    width: 100%;
    margin-bottom: 20px;
    display: flex;
    justify-content: center;
  }
  .formbox {
    width: 400px;
    margin: 50px auto;
    max-width: 92%;
    .formtitle {
      margin: 40px 0 40px;
      text-align: center;
      font-size: 24px;
      font-family: Microsoft YaHei;
      font-weight: bold;
      // line-height: 72px;
      color: #333333;
      opacity: 1;
    }
    // .formtitle2 {
    //   margin: 40px 0 100px !important;
    // }
    .nextbtn {
      display: block;
      width: 100%;
      height: 50px;
      margin: 40px auto 20px;
    }
    .nextbtn2 {
      display: inline-block;
      width: 45%;
      height: 50px;
      margin: 46px auto;
      margin: 10px 2%;
    }
    .fs {
      margin-left: 20px;
      font-size: 14px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      line-height: 30px;
      color: #5688e8;
      opacity: 1;
      text-decoration: underline;
      cursor: pointer;
    }
    .wsd {
      margin-left: 20px;
    }
    .zfs {
      font-size: 14px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      line-height: 30px;
      color: #5688e8;
      opacity: 1;
      text-decoration: underline;
      cursor: pointer;
    }
    .oktitle {
      font-size: 36px;
      font-family: Microsoft YaHei;
      font-weight: bold;
      line-height: 28px;
      color: #5688e8;
      margin: 100px 0 40px;
      text-align: center;
    }
    .okcontent {
      margin: 40px;
      text-align: center;
      font-size: 14px;
      color: #333333;
      line-height: 28px;
    }
  }
}
.goback {
  position: absolute;
  bottom: 0px;
  left: 20px;
  font-size: 12px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  line-height: 66px;
  color: #333333;
  opacity: 1;
  cursor: pointer;
  span {
    margin-left: 10px;
  }
}
@media only screen and (min-width: $screen-md){
  .maxScreen{
    box-shadow: 0px 10px 30px rgba(111, 141, 216, 0.1);
    margin: -100px auto;
   min-height: 500px;
  }
}
</style>
